package com.gxa.consumer.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.common.result.BusinessException;
import com.gxa.common.result.CodePrefixCode;
import com.gxa.common.util.CodeNoUtil;
import com.gxa.consumer.api.dto.AccountRegisterDTO;
import com.gxa.consumer.api.dto.ConsumerDTO;
import com.gxa.consumer.api.dto.ConsumerRegisterDTO;
import com.gxa.consumer.common.ConsumerErrorCode;
import com.gxa.consumer.entity.Consumer;
import com.gxa.consumer.mapper.ConsumerMapper;
import com.gxa.consumer.service.AccountService;
import com.gxa.consumer.service.ConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ConsumerServiceImpl extends ServiceImpl<ConsumerMapper, Consumer> implements ConsumerService {


    @Autowired
    private AccountService accountService;

    /**
     * 检测用户是否存在
     * @param mobile
     * @return
     */
    @Override
    public Integer checkMobile(String mobile) {
        return getByMobile(mobile)!=null?1:0;
    }

    private ConsumerDTO getByMobile(String mobile){
        Consumer consumer=getOne(new QueryWrapper<Consumer>().lambda().eq(Consumer::getMobile,mobile));
        return convertConsumerEntityToDTO(consumer);
    }

    /**
     * 用户注册
     * @param consumerRegisterDTO
     * @return
     */
    @Override
    public void register(ConsumerRegisterDTO consumerRegisterDTO) {
        if(checkMobile(consumerRegisterDTO.getMobile())==1){
            log.info("用户不存在!");
            throw new BusinessException(ConsumerErrorCode.E_140107);
        }

        //保存用户信息
        Consumer consumer=new Consumer();
        BeanUtils.copyProperties(consumerRegisterDTO, consumer);
        consumer.setUsername(CodeNoUtil.getNo(CodePrefixCode.CODE_NO_PREFIX));
        consumerRegisterDTO.setUsername(consumer.getUsername());
        consumer.setUserNo(CodeNoUtil.getNo(CodePrefixCode.CODE_REQUEST_PREFIX));
        consumer.setIsBindCard(0);
        save(consumer);

        //注册账户信息
        AccountRegisterDTO accountRegisterDTO=new AccountRegisterDTO();
        BeanUtils.copyProperties(consumerRegisterDTO, accountRegisterDTO);
        accountService.register(accountRegisterDTO);

    }

    /**
        * entity转为dto
        * @param entity
        * @return
     **/
    private ConsumerDTO convertConsumerEntityToDTO(Consumer entity) {
        if (entity == null) {
            return null;
        }
        ConsumerDTO dto = new ConsumerDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

}
